package com.mylib.widget;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.mylib.libcore.R;
import com.mylib.libcore.adapter.BaseDelegateAdapter;
import com.mylib.libcore.utils.UIUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/12/20-9:38
 * @description 自定义RefreshCustomRecycleViewLayout-适合复杂布局
 **/
public class RefreshCustomRecycleViewLayout extends LinearLayout {
    private Context mContext;
    private View mView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout ll_load_more;
    private TextView tv_load_more;
    private ProgressBar progressBar;
    private DelegateAdapter delegateAdapter;
    private List<DelegateAdapter.Adapter> mAdapters = new LinkedList<>();
    private boolean canLoadMore = true;
    private boolean canRefresh = true;
    private boolean canLoad = true;
    private static final int ONLOAD = 0;
    private static final int NOMOREDATA = 1;


    public RefreshCustomRecycleViewLayout(Context context) {
        this(context, null);
    }

    public RefreshCustomRecycleViewLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RefreshCustomRecycleViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    //上拉刷新监听
    public onSwRefresh onSwRefresh;
    public interface onSwRefresh{
        void onRefresh();
    }
    public void setSwRefresh(onSwRefresh onSwRefresh){
        this.onSwRefresh = onSwRefresh;
    }

    //添加滑动底部监听
    public onScrolledBottomListener onScrolledBottomListener;
    public interface onScrolledBottomListener{
        void onScrolledBottom();
    }
    public void setOnScrolledBottomListener(onScrolledBottomListener onScrolledBottomListener){
        this.onScrolledBottomListener = onScrolledBottomListener;
    }

    //定义一个接口对象listerner
    private IvBackClickListener listener;
    //获得接口对象的方法。
    public void setOnIvBackClickListener(IvBackClickListener listener) {
        this.listener = listener;
    }
    //定义一个接口
    public interface  IvBackClickListener{
        public void onClck();
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = inflater.inflate(R.layout.refresh_recycleview_layout, this, true);
        ll_load_more = (LinearLayout)mView.findViewById(R.id.ll_load_more);
        tv_load_more = (TextView) mView.findViewById(R.id.tv_load_more);
        progressBar = (ProgressBar)mView.findViewById(R.id.loading_process);
        recyclerView = (RecyclerView) mView.findViewById(R.id.recycler);
        swipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.srl_refresh);
        initRefresh();
        initRecyclerView();
    }

    //初始化-SwipeRefreshLayout
    private void initRefresh(){
        swipeRefreshLayout.setColorSchemeResources(R.color.srl_pink, R.color.srl_pink2, R.color.srl_pink3, R.color.srl_pink4, R.color.srl_pink5);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(!UIUtils.isEmpty(onSwRefresh)){
                    if(canRefresh){
                        onSwRefresh.onRefresh();
                        setCanLoadMore(true);
                    }else {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }else {
                    swipeRefreshLayout.setRefreshing(false);
                }

            }
        });
    }

    //初始化-recycleView
    private void initRecyclerView() {
        recyclerView.setNestedScrollingEnabled(false);
        //初始化
        //创建VirtualLayoutManager对象
        MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(mContext);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        // recyclerView.setNestedScrollingEnabled(false);
        //设置回收复用池大小，（如果一屏内相同类型的 View 个数比较多，需要设置一个合适的大小，防止来回滚动时重新创建 View）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
//        //用空间换时间，来提高滚动的流畅性。
//        recyclerView.setDrawingCacheEnabled(true);
//        recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        //设置适配器
        delegateAdapter = new DelegateAdapter(new VirtualLayoutManager(mContext), true);
        recyclerView.setAdapter(delegateAdapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                try {
                    if(dy<0){
                        ll_load_more.setVisibility(GONE);
                        progressBar.setVisibility(GONE);
                        tv_load_more.setVisibility(View.GONE);
                    }
                    //解决mRecyclerView与mSwipeRefreshLayout在部分机型上滑动冲突
                    swipeRefreshLayout.setEnabled(recyclerView.getChildCount() == 0 || recyclerView.getChildAt(0).getTop() >= 0);
                    //得到当前显示的最后一个item的view
                    View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount()-1);
                    //得到lastChildView的bottom坐标值
                    int lastChildBottom = lastChildView.getBottom();
                    //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
                    int recyclerBottom =  recyclerView.getBottom()-recyclerView.getPaddingBottom();
                    //通过这个lastChildView得到这个view当前的position值
                    int lastPosition  = recyclerView.getLayoutManager().getPosition(lastChildView);
                    //判断lastChildView的bottom值跟recyclerBottom
                    //判断lastPosition是不是最后一个position
                    //如果两个条件都满足则说明是真正的滑动到了底部
                    if(lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount()-1 ){
                        if(canLoad){
                            if(canLoadMore){
                                setLoadMoreState(ONLOAD);
                            }else {
                                setLoadMoreState(NOMOREDATA);
                            }
                            onScrolledBottomListener.onScrolledBottom();
                        }else {
                            ll_load_more.setVisibility(GONE);
                            progressBar.setVisibility(GONE);
                            tv_load_more.setVisibility(View.GONE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //加载状态

    private void setLoadMoreState(int state){
        switch (state){
            case ONLOAD:
                ll_load_more.setVisibility(VISIBLE);
                progressBar.setVisibility(VISIBLE);
                tv_load_more.setVisibility(View.VISIBLE);
                tv_load_more.setText("加载中...");
                break;
            case NOMOREDATA:
                ll_load_more.setVisibility(VISIBLE);
                progressBar.setVisibility(GONE);
                tv_load_more.setVisibility(View.VISIBLE);
                tv_load_more.setText("已全部加载");
                break;
        }
    }

    //添加子adapter
    public void addChildAdapter(BaseDelegateAdapter childAdapter){
        mAdapters.add(childAdapter);
    }

    public int getSize(){
        if(!UIUtils.isEmpty(mAdapters)) {
            return mAdapters.size();
        }else {
            return 0;
        }
    }

    //移除子adapter
    public void removeChildAdapter(int index){
        if(!UIUtils.isEmpty(mAdapters)) {
          if(index<mAdapters.size()){
              mAdapters.remove(index);
              delegateAdapter.notifyDataSetChanged();
              recyclerView.requestLayout();
          }
        }
    }

    //将所有子adapter填充模板
    public void setFillTemplate(){
        if (!UIUtils.isEmpty(mAdapters)) {
            delegateAdapter.notifyDataSetChanged();
            delegateAdapter.setAdapters(mAdapters);
            recyclerView.requestLayout();
        }
    }

    //清除所有子adapter填充模板
    public void clearAdapter(){
        if (!UIUtils.isEmpty(mAdapters)) {
            mAdapters.clear();
            delegateAdapter.clear();
            delegateAdapter.notifyDataSetChanged();
            recyclerView.requestLayout();
        }
    }

    //更新所有子adapter填充模板
    public void notifyAdapter(){
        if (!UIUtils.isEmpty(delegateAdapter)) {
            delegateAdapter.clear();
            delegateAdapter.setAdapters(mAdapters);
            delegateAdapter.notifyDataSetChanged();
            recyclerView.requestLayout();
        }
    }

    //关闭刷新
    public void finishRefresh(){
        if(swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        if(tv_load_more.getVisibility() == VISIBLE){
            tv_load_more.setVisibility(GONE);
        }
        if(progressBar.getVisibility() == VISIBLE){
            progressBar.setVisibility(GONE);
        }
        if(ll_load_more.getVisibility() == VISIBLE){
            ll_load_more.setVisibility(GONE);
        }
        if(!canLoad){
            if(!canLoadMore){
                setLoadMoreState(NOMOREDATA);
            }
        }
    }



    public boolean isCanRefresh() {
        return canRefresh;
    }

    public void setCanRefresh(boolean canRefresh) {
        this.canRefresh = canRefresh;
        if(canRefresh==false){
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public boolean isCanLoadMore() {
        return canLoadMore;
    }

    public void setCanLoadMore(boolean canLoadMore) {
        this.canLoadMore = canLoadMore;
        if(!canLoadMore){
            setLoadMoreState(NOMOREDATA);
        }
    }

    public boolean isCanLoad() {
        return canLoad;
    }

    public void setCanLoad(boolean canLoad) {
        this.canLoad = canLoad;
        if(!canLoad){
            ll_load_more.setVisibility(GONE);
            progressBar.setVisibility(GONE);
            tv_load_more.setVisibility(View.GONE);
        }

    }
}
